import * as Koa from 'koa';
import { addInfo, delInfo, updateInfo, searchInfo } from "../entity/info";
import { joinDefaultFields } from "../utils/index";
const dayjs = require("dayjs");
// TODO：commonjs 模式下引用 esmodule 模块
let nanoid: any = null;
(async () => {
  nanoid = (await eval("import('nanoid')")).nanoid;
})();

const errorMsg = `服务器错误：${'info'}`;
const successMsg = `成功：${'info'}`;

export default class InfoService {
  /**
   * 添加
   * @param ctx 
   */
  addInfo = async (ctx: Koa.Context) => {
    try {
      const info = ctx.request.body;
      // 新增
      const _info = joinDefaultFields(info, "infoFields");
      _info.iid = nanoid(18);
      _info.create_time = dayjs().format("YYYY-MM-DD HH:mm:ss");
      const result: any = _info && await addInfo(ctx, _info);
      if (!result) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else if (!result.success) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else {
        ctx.success(null, successMsg);
      }
    } catch (error) {
      ctx.fail(null, errorMsg, -1);
    }
  };

    /**
   * 删除
   * @param ctx 
   */
  delInfo = async (ctx: Koa.Context) => {
    try {
      const { iid } = ctx.request.body;
      if (!iid || !iid.length) return ctx.fail(null, "iid不能为空", -1);
      const iids = Array.isArray(iid)? iid : [iid];
      let condition = `iid IN (${iids.map((i) => `"${i}"`).join(",")})`;
      const result: any =  !!iids.length && await delInfo(ctx, { condition });
      if (!result) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else if (!result.success) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else {
        ctx.success(null, successMsg);
      }
    } catch (error) {
      ctx.fail(null, errorMsg, -1);
    }
  };

    /**
   * 修改
   * @param ctx 
   */
  updateInfo = async (ctx: Koa.Context) => {
    try {
      const info = ctx.request.body;
      info.update_time = dayjs().format("YYYY-MM-DD HH:mm:ss"); // 最后的更新时间
      const result: any = info && await updateInfo(ctx, info);
      if (!result) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else if (!result.success) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else {
        ctx.success(null, successMsg);
      }
    } catch (error) {
      ctx.fail(null, errorMsg, -1);
    }
  };

  /**
   * 查询
   * @param ctx 
   */
  searchInfo = async (ctx: Koa.Context) => {
    try {
      const params = ctx.request.body;
      const { iid, page_num, text_content } = params || {}; // 查询条件
      // 相等的条件
      let condition = "";
      let equals: string | string[] = [];
      iid && (equals.push(` iid = "${iid}"`));
      page_num && (equals.push(` page_num = "${page_num}"`));
      text_content && (equals.push(` text_content LIKE "%${text_content}%"`));
      equals = equals.join(" AND");
      equals && (condition += `WHERE ${equals}`);
      const result: any = await searchInfo(ctx, { condition });
      if (!result) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else if (!result.success) {
        ctx.fail(null, result.msg || errorMsg, -1);
      } else {
        ctx.success(result.data || [], successMsg);
      }
    } catch (error) {
      ctx.fail(null, errorMsg, -1);
    }
  };
}
